//
//  KKAnalytics.m
//  KKAnalytics
//
//  Created by Win Jay on 2019/8/23.
//  Copyright © 2019年 Win Jay. All rights reserved.
#import "KKAnalytics.h"
#import "FBSDKCoreKit.h"
#import "FirebaseCore.h"
#import "FirebaseAnalytics/FirebaseAnalytics.h"
#import "AdSupport/AdSupport.h"
#import "Adjust.h"
#import "ThinkingSDK/ThinkingAnalyticsSDK.h"

@interface KKAnalytics()<AdjustDelegate>

@property BOOL canAutoTrackThinkingDataEvent;

@end
@implementation KKAnalytics
+ (instancetype)shareManager{
    static KKAnalytics *manager=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [KKAnalytics new];
        
    });
    return manager;
}

- (NSString *)getAdvertisementID{
        if([[[ASIdentifierManager sharedManager]advertisingIdentifier]UUIDString]){
            return [[[ASIdentifierManager sharedManager]advertisingIdentifier]UUIDString];
        }else{
            return @"";
        }
}

#pragma mark   Adjust
- (void)adjustAttributionChanged:(ADJAttribution *)attribution{
    NSLog(@"===========归因信息%@",attribution.network);
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:attribution.network forKey:@"KK_AD_SOURCE"];
    [defaults synchronize];
    [self setTKUser:@{@"user_source":attribution.network}];
}

- (void)initAdjust:(NSString *)app_id{
    if(_isInitAdjust){
        NSLog(@"Adjust已完成初始化");
        return;
    }
    ADJConfig *config = [ADJConfig configWithAppToken:app_id
                                    environment:ADJEnvironmentProduction];
    [config setDelegate:self];
    [Adjust appDidLaunch:config];
    _isInitAdjust=YES;
}
- (void)initAdjust:(NSString *)app_id secretID:(NSUInteger)secretId info1:(NSUInteger)info1 info2:(NSUInteger)info2 info3:(NSUInteger)info3 info4:(NSUInteger)info4{
    if(_isInitAdjust){
        NSLog(@"Adjust已完成初始化");
        return;
    }
    ADJConfig *config = [ADJConfig configWithAppToken:app_id
                                          environment:ADJEnvironmentProduction];
    [config setAppSecret:secretId info1:info1 info2:info2 info3:info3 info4:info4];
    [config setDelegate:self];
    [Adjust appDidLaunch:config];
    _isInitAdjust=YES;
}
- (void)logAdjustEvent:(NSString *)eventToken{
    if(!_isInitAdjust)
        return;
    if(eventToken)
        [Adjust trackEvent:[ADJEvent eventWithEventToken:eventToken]];
}
- (void)logAdjustRevenue:(NSString *)eventToken price:(double)prices currencyCode:(NSString *)code{
    if(!_isInitAdjust){
        return;
    }
    if(eventToken){
        ADJEvent *event=[ADJEvent eventWithEventToken:eventToken];
        [event setRevenue:prices currency:code];
        [Adjust trackEvent:event];
    }
}
- (void)logAdjsutAdRevenue:(NSData *)data{
    if(data){
        [Adjust trackAdRevenue:ADJAdRevenueSourceMopub payload:data];
    }
}

#pragma mark   ThinkingData

- (void)initThinkingData:(NSString *)app_id{
    if(_isInitThinkingData){
         NSLog(@"已经初始化数数");
         return;
     }
     [ThinkingAnalyticsSDK startWithAppId:app_id
                                  withUrl:@"http://analytics.socialcube.me/"];
    
     [self setThinkingDataAutoTrack];
     _isInitThinkingData=YES;;
}


- (void)setThinkingDataDebubgModel{
    [ThinkingAnalyticsSDK setLogLevel:TDLoggingLevelDebug];
}
- (void)setThinkingDataAutoTrack{
     [[ThinkingAnalyticsSDK sharedInstance]enableAutoTrack:
     ThinkingAnalyticsEventTypeAppStart|
     ThinkingAnalyticsEventTypeAppEnd|
     ThinkingAnalyticsEventTypeAppInstall|
    ThinkingAnalyticsEventTypeAppViewCrash|
      ThinkingAnalyticsEventTypeAppViewScreen];
}

- (void)logTKEvent:(NSString *)trackName params:(NSDictionary *)dic{
    if(!_isInitThinkingData)
        return;
    if(dic){
        [[ThinkingAnalyticsSDK sharedInstance]track:trackName properties:dic];
    }else{
        [[ThinkingAnalyticsSDK sharedInstance]track:trackName];
    }
}
- (void)logFacebookFirebaseTKEvent:(NSString *)eventName params:(NSDictionary *)dic{
    [self logFacebookEvent:eventName params:dic];
    [self logFirebaseEvent:eventName params:dic];
    [self logTKEvent:eventName params:dic];
}

- (void)setTKVisitorID:(NSString *)visitorID{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]identify:visitorID];
    [self setThinkingDataAutoTrack];
}
- (void)setTKLoginID:(NSString *)loginID{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]login:loginID];
}
- (void)setTKLogout{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]logout];
}
- (void)deleteTKUser{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]user_delete];
}
- (void)setTKSuperProperties:(NSDictionary *)properties{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]setSuperProperties:properties];
}
- (void)unSetTKSuperProperties:(NSString *)propertyName{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]unsetSuperProperty:propertyName];
}
- (void)setTKTimeTrackEvent:(NSString *)timeName{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]timeEvent:timeName];
}
- (void)setTKUser:(NSDictionary *)userInfo{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]user_set:userInfo];
}
- (void)setTKUserOnce:(NSDictionary *)userInfo{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]user_setOnce:userInfo];
}
- (void)setTKUserAdd:(NSDictionary *)addInfo{
    if(!_isInitThinkingData)
        return;
    [[ThinkingAnalyticsSDK sharedInstance]user_add:addInfo];
}
#pragma mark   Facebook
- (void)initFacebook:(NSString *)fb_id{
    if(_isInitFacebook){
        NSLog(@"已经初始化Facebook");
        return;
    }
    [FBSDKSettings setAppID:fb_id];
    _isInitFacebook=YES;
}
- (void)logFacebookEvent:(NSString *)eventName params:(NSDictionary *__nullable)dic{
    if(!_isInitFacebook)
        return;
    if(dic){
        [FBSDKAppEvents logEvent:eventName parameters:dic];
    }else{
        [FBSDKAppEvents logEvent:eventName];
    }
}
#pragma mark   Firebase
- (void)initFirebase{
    if(_isInitFirebase){
        NSLog(@"已经初始化Facebook");
        return;
    }
    [FIRApp configure];
    _isInitFirebase=YES;
}

- (void)logFirebaseEvent:(NSString *)eventName params:(NSDictionary *__nullable)dic{
    if(!_isInitFirebase)
        return;
    if(dic){
        [FIRAnalytics logEventWithName:eventName parameters:dic];
    }else{
        [FIRAnalytics logEventWithName:eventName parameters:nil];
    }
}
- (void)setFirebaseUserProperty:(NSString *)property propertyName:(NSString*)forName{
    if(!_isInitFirebase){
        return;
    }
    if(property==nil||forName==nil){
        NSLog(@"firebase参数有误");
        return;
    }
    [FIRAnalytics setUserPropertyString:property forName:forName];
}


- (void)validateReceiptViaServer:(NSString *)transaction_id purchasePoint:(NSString *)point{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:RECEIPT_VALIDATION_URL]];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [request setHTTPMethod:@"POST"];
    NSData *receiptData = [NSData dataWithContentsOfURL:[[NSBundle mainBundle]appStoreReceiptURL]];
    if (!receiptData) {
        return;
    }
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:0];
    NSString * campaign = [Adjust attribution].campaign;
    if(campaign){
        [params setObject:campaign forKey:@"ad_campaign_provider"];
    }else{
        [params setObject:@"" forKey:@"ad_campaign_provider"];
    }
    NSString * adgroup = [Adjust attribution].adgroup;
    if(adgroup){
        [params setObject:adgroup forKey:@"ad_group_name"];
    }else{
        [params setObject:@"" forKey:@"ad_group_name"];
    }
    NSDictionary *attribution=[Adjust attribution].dictionary;
    if(attribution){
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:attribution options:NSJSONWritingPrettyPrinted error:&error];
        NSString * str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        if(str){
            [params setObject:str forKey:@"adjust_attribution"];
        }else{
            [params setObject:@"" forKey:@"adjust_attribution"];
        }
    }else{
        [params setObject:@"" forKey:@"adjust_attribution"];
    }
    NSString * bundleID= [[NSBundle mainBundle] bundleIdentifier];
    [params setObject:bundleID forKey:@"bundle_id"];
    NSString * conunty = [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode];
    if(conunty){
        [params setObject:conunty forKey:@"country"];
    }else{
        [params setObject:@"US" forKey:@"country"];
    }
    if([[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]){
        [params setObject:[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] forKey:@"idfa"];
    }else{
        [params setObject:@"" forKey:@"idfa"];
    }
    NSString *token=@"";
    if([[NSUserDefaults standardUserDefaults]objectForKey:@"KK_PUSH_TOKEN"]){
        token=[[NSUserDefaults standardUserDefaults]objectForKey:@"KK_PUSH_TOKEN"];
    }
    if(token){
        [params setObject:token forKey:@"push_token"];
    }
    if(transaction_id){
        [params setObject:transaction_id forKey:@"original_transaction_id"];
    }else{
        [params setObject:@"" forKey:@"original_transaction_id"];
    }
    NSString *shortVersion=[[[NSBundle mainBundle] infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    [params setObject:shortVersion forKey:@"product_version"];
    
    [params setObject:point forKey:@"purchase_point"];
    [params setObject:receiptString forKey:@"receipt"];
    NSString * trackName = [Adjust attribution].trackerName;
    if(trackName)
    {
        [params setObject:trackName forKey:@"tracker_name"];
    }else{
        [params setObject:@"" forKey:@"tracker_name"];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:jsonData];
    [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            if(data){
                NSError *err;
                id dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
                if([[dic objectForKey:@"status"] isEqualToString:@"success"]){
                }
            }
        }else {
            NSLog(@"iap验证输入失败%@",error);
        }
    }]resume];
}
- (void)registerNotificationSetting:(UIApplication *)application{
    [application registerForRemoteNotifications];
}
- (void)registerNotificationWithDiveceToken:(NSData *)diviceToken{
    NSString *deviceID = [[[[diviceToken description]stringByReplacingOccurrencesOfString:@"<" withString:@""]stringByReplacingOccurrencesOfString:@">" withString:@""]stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:deviceID forKey:@"KK_PUSH_TOKEN"];
    [defaults synchronize];
}
- (void)registerNotificationWhenAppLaunch:(UIApplication *)application{
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIUserNotificationTypeSound];
    }
}

-(NSDictionary *)convertStringToDictionary:(NSString *)json{
    if(json==nil){
        return  nil;
    }
    NSData* data=[json dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error=nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                        options:NSJSONReadingMutableContainers
                                                          error:&error];
    if(error){
        NSLog(@"数据解析失败%@",error);
        return  nil;
    }
    return dic;
}
#pragma mark   Unity invoke

extern "C"{
    void logAdjustEvent(char * eventToken){
        if(eventToken){
            [[KKAnalytics shareManager]logAdjustEvent:[NSString stringWithUTF8String:eventToken]];
        }
        
    }
    void logAdjustRevenue(char *eventToken,double price,char*currentyCode){
        [[KKAnalytics shareManager]logAdjustRevenue:[NSString stringWithUTF8String:eventToken] price:price currencyCode:[NSString stringWithUTF8String:currentyCode]];
        
    }
    void logFacebookEvent(char *eventName,char*json){
        if(json){
                   [[KKAnalytics shareManager]logFirebaseEvent :[NSString stringWithUTF8String:eventName] params:[[KKAnalytics shareManager]convertStringToDictionary:[NSString stringWithUTF8String:json]]];
        
        }else{
               [[KKAnalytics shareManager]logFacebookEvent:[NSString stringWithUTF8String:eventName] params:[[KKAnalytics shareManager]convertStringToDictionary:nil]];
        }
    }
    void logFirebaseEvent(char *eventName,char*json){
        if(json){
            [[KKAnalytics shareManager]logFirebaseEvent:[NSString stringWithUTF8String:eventName] params:[[KKAnalytics shareManager]convertStringToDictionary:[NSString stringWithUTF8String:json]]];
            
            
        }else{
            [[KKAnalytics shareManager]logFirebaseEvent:[NSString stringWithUTF8String:eventName] params:[[KKAnalytics shareManager]convertStringToDictionary:nil]];
        }
    }
    void logFacebookFirebaseEvent(char *eventName,char *jsonParams){
        
    }
    void logFirebaseUserProperty(char*propertyName,char*forName){
        [[KKAnalytics shareManager]setFirebaseUserProperty:[NSString stringWithUTF8String:propertyName] propertyName:[NSString stringWithUTF8String:forName]];
    }
    void logFacebookFirebaseThinkEvent(char *eventName,char*jsonParams){
        if(jsonParams){
            NSDictionary *params=[[KKAnalytics shareManager]convertStringToDictionary:[NSString stringWithUTF8String: jsonParams]];
            [[KKAnalytics shareManager]logFacebookFirebaseTKEvent:[NSString stringWithUTF8String:eventName] params:params];
        }else{
           [[KKAnalytics shareManager]logFacebookFirebaseTKEvent:[NSString stringWithUTF8String:eventName] params:nil];
        }
    }
    void setThinkTrackEvent(char *eventName,char *json){
        if(json){
            NSDictionary *dic=[[KKAnalytics shareManager]convertStringToDictionary:[NSString stringWithUTF8String:json]];
            [[KKAnalytics shareManager]logTKEvent:[NSString stringWithUTF8String:eventName] params: dic];
        }else{
               [[KKAnalytics shareManager]logTKEvent:[NSString stringWithUTF8String:eventName] params: nil];
        }
    }
    void setThinkVistorID(char *vistorID){
        [[KKAnalytics shareManager]setTKVisitorID:[NSString stringWithUTF8String:vistorID]];
    }
    void setThinkLoginID(char *loginID){
        [[KKAnalytics shareManager]setTKLoginID:[NSString stringWithUTF8String:loginID]];
    }
    void setThinkLogout(){
        [[KKAnalytics shareManager]setTKLogout];
    }
    void setThinkSuperProperties(char *json){
        if(json){
             NSDictionary *params=[[KKAnalytics shareManager]convertStringToDictionary:[NSString stringWithUTF8String: json]];
            [[KKAnalytics shareManager]setTKSuperProperties:params];
        }
    }
    void unsetThinkProperties(char *propertyName){
        if(propertyName){
            [[KKAnalytics shareManager]unSetTKSuperProperties:[NSString stringWithUTF8String:propertyName]];
        }
    
    }
    void setThinkTimeTrackEvent(char *eventName){
        [[KKAnalytics shareManager]setTKTimeTrackEvent:[NSString stringWithUTF8String:eventName]];
    }
    void setThinkUser(char *useInfoJson){
        if(useInfoJson){
            NSDictionary *params=[[KKAnalytics shareManager]convertStringToDictionary:[NSString stringWithUTF8String: useInfoJson]];
            [[KKAnalytics shareManager]setTKUser:params];
        }
    }
    void setThinkUserOnce(char *useInfoJson){
        if(useInfoJson){
            NSDictionary *params=[[KKAnalytics shareManager]convertStringToDictionary:[NSString stringWithUTF8String: useInfoJson]];
            [[KKAnalytics shareManager]setTKUserOnce:params];
        }
       
    }
    void setThinkUserAdd(char *useInfoJson){
        if(useInfoJson){
            NSDictionary *params=[[KKAnalytics shareManager]convertStringToDictionary:[NSString stringWithUTF8String: useInfoJson]];
            [[KKAnalytics shareManager]setTKUserAdd:params];
        }
    }
    void deleteThinkUser(){
        [[KKAnalytics shareManager]deleteTKUser];
    }
    void validateReceiptToServer(char *original_transaction_id,char *purchase_point){
        [[KKAnalytics shareManager]validateReceiptViaServer:[NSString stringWithUTF8String:original_transaction_id] purchasePoint:[NSString stringWithUTF8String:purchase_point]];
    }
}


@end
